/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.application.commands.generate;

import com.nanosn.coffeemaker.Project;
import com.nanosn.coffeemaker.databaseproject.persistence.DatabaseJDBCConfiguration;
import com.nanosn.coffeemaker.freemarker.FMPP;
import com.nanosn.util.Jar;
import com.nanosn.util.parsers.commandline.Command;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author selkhateeb
 */
public class Persistence implements Command {

    @Override
    public void run(String[] args) throws Exception {
        //get project name
        //get model callses as string array
        //process it
        final String projectDir = Project.PWD;

        String srcFile = Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                         + File.separator + "database"
                         + File.separator + "persistenceClasses.xml.ftl";

        /* To generate the Settings file we do not need to pass any variables
         * However, for the manage.sh we need to determine the location
         * of the Main class .. or the Jar file
         */
        HashMap<String, Object> variables = new HashMap<String, Object>();

        Class[] classes = Project.getClassLoader().getModelClasses();

        ArrayList<String> stringClasses = new ArrayList<String>();

        for (Class class1 : classes) {
            stringClasses.add(class1.getName());
        }

        DatabaseJDBCConfiguration conf = new DatabaseJDBCConfiguration();
        variables.put("Classes", stringClasses);
        variables.put("ProjectName", Project.getSettings().getRootPackage());
        variables.put("ConnectionURL", conf.getConnectionURL());
        variables.put("ConnectionDriverName", conf.getConnectionDriverName());

        if (!Project.getApplicationJar().isDirectory()) {

            String tmpFile = Project.TMP + Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                             + File.separator + "database"
                             + File.separator + "persistenceClasses.xml.ftl";
            //Extract files to temp directory
            Jar.ExtractSingleFile(Project.getApplicationJar(), srcFile, tmpFile);
            FMPP.RunFMPP(tmpFile, projectDir, variables);
        }
        else {
            FMPP.RunFMPP(srcFile, projectDir, variables);
        }
    }

    @Override
    public String getHelp() {
        return "Generates the persistence xml file";
    }
}
